/*
 * 标签文章列表页面组件 - Tag Posts Page Component
 * 显示特定标签下的所有文章，布局参照首页但移除顶部大图区域
 */
import { Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'umi';
import CategoryTags from '../../components/CategoryTags';
import FadeInCard from '../../components/FadeInCard';
import SidebarTags from '../../components/SidebarTags';

import styles from './index.less';

// 引入图片资源
// import picImage from '../../assets/images/pic.png';
const picImage =
  'https://iiiu-assets-images.oss-cn-beijing.aliyuncs.com/assets/test.jpg?Expires=1756307172&OSSAccessKeyId=TMP.3KtH5yADB6FBiLcodsY4PjZoRWiHAp7TX3bJSF8tsyY5b4bSveBbwYfjfMZyPLJJAWvoxb23EJfkPnsemai1fjLjnEWYF7&Signature=9MGG6ukYcKa%2BnlPmx3ptISYRxZU%3D';

// 引入服务端API
import { getAllCategory } from '@/services/Category/api';
import { getPostIdsByTagId } from '@/services/Tag/api';

// 使用从models导入的接口定义
import { Category } from '@/models/category';
import { Post } from '../../models/post';

const TagPosts: React.FC = () => {
  const { tagId } = useParams<{ tagId: string }>();
  const navigate = useNavigate();

  // 状态管理
  const [posts, setPosts] = useState<Post[]>([]);
  const [filteredPosts, setFilteredPosts] = useState<Post[]>([]);
  const [categoryList, setCategoryList] = useState<Category[]>([]);
  const [, setSelectedCategoryId] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [error] = useState<string | null>(null);

  useEffect(() => {
    const fetchTagPosts = async () => {
      try {
        console.log('开始获取标签文章，tagId:', tagId);
        const postsResponse = await getPostIdsByTagId(Number(tagId));
        console.log('getPostIdsByTagId响应:', postsResponse);

        let postsData: Post[] = [];
        if (Array.isArray(postsResponse)) {
          // 直接数组响应
          console.log('检测到直接数组响应');
          postsData = postsResponse;
        } else if (postsResponse.success && postsResponse.data) {
          // ApiResponse包装响应
          console.log('检测到ApiResponse包装响应');
          postsData = postsResponse.data;
        }

        console.log('解析后的postsData:', postsData);
        setPosts(postsData);
        setFilteredPosts(postsData);
      } catch (error) {
        console.error('获取标签文章错误:', error);
        setPosts([]);
        setFilteredPosts([]);
      } finally {
        setLoading(false);
      }
    };

    const fetchCategoryList = async () => {
      try {
        const categoriesResponse = await getAllCategory();

        if (categoriesResponse.success && categoriesResponse.data) {
          setCategoryList(categoriesResponse.data);
        } else {
          console.error('获取分类列表失败');
        }
      } catch (error) {
        console.error('获取分类列表错误:', error);
      }
    };

    fetchTagPosts();
    fetchCategoryList();
  }, [tagId]);

  // 处理分类选择
  const handleCategorySelect = (categoryId: number | null) => {
    setSelectedCategoryId(categoryId);

    if (categoryId === null) {
      // 如果选择"全部"，显示所有文章
      setFilteredPosts(posts);
    } else {
      // 根据分类ID过滤文章
      const filtered = posts.filter((post) => post.categoryId === categoryId);
      setFilteredPosts(filtered);
    }
  };

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" />
      </div>
    );
  }

  if (error) {
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorMessage}>{error}</div>
      </div>
    );
  }

  return (
    <div className={styles.tagPostsPage}>
      {/* Content Section - 移除了顶部大图区域 */}
      <section className={styles.contentSection}>
        <div className={styles.container}>
          {/* 页面标题 */}
          <div className={styles.pageHeader}>
            <h1 className={styles.pageTitle}>
              标签文章列表
              {filteredPosts.length > 0 && (
                <span className={styles.postCount}>
                  ({filteredPosts.length}篇文章)
                </span>
              )}
            </h1>
          </div>

          {/* Main Content Area */}
          <div className={styles.mainContent}>
            {/* Articles Section */}
            <section className={styles.articlesSection}>
              {/* 分类标签 */}
              <div className={styles.categoryTagsContainer}>
                <CategoryTags
                  categories={categoryList}
                  onCategorySelect={handleCategorySelect}
                />
              </div>

              {/* 文章列表 */}
              {filteredPosts.length > 0 ? (
                <div className={styles.cardGrid}>
                  {filteredPosts.map((item, index) => (
                    <FadeInCard
                      key={item.id}
                      title={item.title}
                      abstractInfo={item.abstractInfo}
                      image={picImage}
                      delay={index * 200}
                      onClick={() => navigate(`/post/${item.id}`)}
                    />
                  ))}
                </div>
              ) : (
                <div className={styles.emptyState}>
                  <div className={styles.emptyIcon}>📝</div>
                  <div className={styles.emptyText}>该标签下暂无文章</div>
                  <div className={styles.emptySubtext}>换个标签试试吧</div>
                </div>
              )}
            </section>

            {/* Sidebar */}
            <aside className={styles.sidebar}>
              <SidebarTags />
            </aside>
          </div>
        </div>
      </section>
    </div>
  );
};

export default TagPosts;
